package com.klikmee.sms.core.base.communicator.starion;

import java.text.MessageFormat;
import java.util.Hashtable;

import org.apache.log4j.Logger;

import com.klikmee.sms.cef.bulk.BulkSender.BulkParams;
import com.klikmee.sms.cef.bulk.EventParams;
import com.klikmee.sms.cef.bulk.starion.BulkEvents;
import com.klikmee.sms.core.base.dao.BulkMessageDAO;
import com.klikmee.sms.core.commons.events.AppEvent;
import com.klikmee.sms.core.commons.events.EventListener;
import com.klikmee.sms.core.model.BulkMessage;

public class StarionBulkSentEventHandler implements EventListener {

	private Logger			logger	= Logger.getLogger( StarionBulkSentEventHandler.class );

	// bulk message dao used to update bulk messages
	private BulkMessageDAO	bulkMessageDao;

	@Override
	public void handleEvent(AppEvent appEvent) {
		if (appEvent.getEventType().equals( BulkEvents.STARTION_BULK_MESSAGE_SENT )) {
			onStarionBulkMessageSent( appEvent );
		}
	}

	/**
	 * Parses HTTP request and updates bulk message with starions message id in
	 * case of success. In case of failure, error is logged and
	 * {@link BulkMessage#getPrividersId()} is populated with error code
	 * 
	 * @param appEvent
	 */
	private void onStarionBulkMessageSent(AppEvent appEvent) {
		// extract event data
		String responseBody = appEvent.<String> getData( EventParams.RESPONSE_BODY );
		Hashtable<BulkParams, Object> bulkParams = appEvent.<Hashtable<BulkParams, Object>> getData( EventParams.BULK_PARAMS );

		// parse response
		BulkStatus bulkStatus = BulkResponseParser.parse( responseBody );
		// find bulk message and update it's status
		Long bulkMessageId = (Long) bulkParams.get( BulkParams.CORE_BULK_MESSAGE_ID );
		BulkMessage bulkMessage = bulkMessageDao.find( bulkMessageId );
		bulkMessage.setPrividersId( bulkStatus.getStartionMessageId() );
		
		bulkMessageDao.edit( bulkMessage );
		logger.info( MessageFormat.format( "Update bulk message [{0}], set provider id to [{1}]", bulkMessage.getId(), bulkMessage.getPrividersId() ) );
	}
	
	public void setBulkMessageDao(BulkMessageDAO bulkMessageDao) {
		this.bulkMessageDao = bulkMessageDao;
	}

}
